package org.apache.ocean;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.jdom.Element;

/**
 * 
 * @author jasonr
 */
public class HighlightResponse extends NamedList<String, HighlightResponse.DocumentHighlight> implements CElement {
	public HighlightResponse() {
	}

	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}

	public HighlightResponse(Element element) {
		for (Element documentHighlightElement : XMLUtil.getChildren("documentHighlight", element)) {
			DocumentHighlight documentHighlight = new DocumentHighlight(documentHighlightElement);
			add(documentHighlight);
		}
	}

	public Element toElement() {
		Element root = new Element("highlights");
		for (DocumentHighlight documentHighlight : getValues()) {
			root.addContent(documentHighlight.toElement());
		}
		return root;
	}

	public void add(DocumentHighlight documentHighlight) {
		add(documentHighlight.guid, documentHighlight);
	}

	public static class DocumentHighlight extends NamedList<String, String> {
		public String guid;

		public DocumentHighlight(Element root) {
			guid = root.getAttributeValue("guid");
			for (Element element : XMLUtil.getChildren(root)) {
				String field = element.getName();
				add(field, element.getText());
			}
		}

		public Element toElement() {
			Element documentHighlightElement = new Element("documentHighlight");
			documentHighlightElement.setAttribute("guid", guid);
			for (NamedList.Entry<String, String> entry : getEntries()) {
				if (entry.value == null)
					continue;
				XMLUtil.createTextElement(entry.key, entry.value, documentHighlightElement);
			}
			return documentHighlightElement;
		}

		public DocumentHighlight(String guid) {
			this.guid = guid;
		}
	}
}
